package com.example.springboot.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.springboot.common.ResultCode;
import com.example.springboot.common.config.JwtTokenUtils;
import com.example.springboot.dao.IntroduceDao;
import com.example.springboot.entity.Account;
import com.example.springboot.entity.Introduce;
import com.example.springboot.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IntroduceService {

    @Resource
    private IntroduceDao introduceDao;

    public List<Introduce> GetAll(){

        return introduceDao.selectAll();
    }
    public Introduce add(Introduce introduce) {
        String title = introduce.getTitle();
        introduce.setTime(DateUtil.now()); //设置当前时间为发布时间
        if (ObjectUtil.isEmpty(title)){
            throw new CustomException(ResultCode.TITLE_ISNULL);
        }
        if (ObjectUtil.isEmpty(introduce.getImg())) {
            introduce.setImg("http://localhost:9090/files/default.png");
        }

        introduceDao.insertSelective(introduce);
        return introduce;
    }


    public Introduce findById(Integer id) {
        return introduceDao.findById(id);
    }




    public void delete(Integer id) {
        introduceDao.deleteByPrimaryKey(id);
    }


    public PageInfo<Introduce> findPage(Introduce search, Integer pageNum, Integer pageSize) {
        Account user = JwtTokenUtils.getCurrentUser();
        if (ObjectUtil.isEmpty(user)) {
            throw new CustomException(ResultCode.USER_NOT_LOGIN);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Introduce> all = findByCondition(search);

        return PageInfo.of(all);
    }

    public List<Introduce> findByCondition(Introduce search) {
        return introduceDao.findBySearch(search);
    }



    public Introduce introduceEdit(Introduce introduce) {

        String introduceName = introduce.getTitle();
//     1.先校验标题是不是为空： 如果用户名，为空，抛出异常
        if (ObjectUtil.isEmpty(introduceName)){
            throw new CustomException(ResultCode.USERNAME_ISNULL);
        }
        introduceDao.updateByPrimaryKeySelective(introduce);

        return introduce;
    }
    public List<Introduce> GetNewData() {
        return introduceDao.getNewdata();
    }

    public Introduce getById(Integer id) {
        return introduceDao.findById(id);
    }

}
